# @Author     ：SEED
# @DateTime   ：2019-08-20  11:14 
# @FileName   ：spare_out.py

from assets.models import SpareOut, SpareParts
from django.http import FileResponse
from common.custom_response import MyResponse
from assets.serializers.spare_out_serializer import SpareOutSerializer, UpdateOutSerializer
from rest_framework import viewsets, status, filters
from django.http import JsonResponse
from common.custom_filter import SpareOutFilter
from _datetime import datetime
from HzrsOps2.settings import BASE_DIR
from docxtpl import DocxTemplate
from rest_framework.views import APIView
from rest_framework.response import Response
from common.custom import CustomPagination, RbacPermission
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework_jwt.authentication import JSONWebTokenAuthentication


class SpareOutViewSet(viewsets.ModelViewSet):
    """
    备件管理
    """
    perms_map = ({'*': 'admin'}, {'*': 'so_all'}, {'get': 'so_list'}, {'post': 'so_create'},
                 {'put': 'so_edit'},
                 {'delete': 'so_delete'})
    queryset = SpareOut.objects.all()
    serializer_class = SpareOutSerializer
    pagination_class = CustomPagination
    filter_class = SpareOutFilter
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    search_fields = (
        'find_date', 'rep_date', 'model', 'sn', 'ip', 'bad_sn', 'bad_pn', 'remarks')
    ordering_fields = ('find_date',)
    ordering = ('-find_date',)
    authentication_classes = (JSONWebTokenAuthentication,)
    permission_classes = (RbacPermission,)

    def get_serializer_class(self):
        # 根据请求类型动态变更serializer
        if self.action == 'list':
            return SpareOutSerializer
        return UpdateOutSerializer

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        sp_id = serializer.data['SpareParts']
        ss = SpareParts.objects.get(id=sp_id)
        if ss.status is False:
            return MyResponse('当前选择备件已经出库，请重新选择', status=status.HTTP_400_BAD_REQUEST)
        else:
            ss.status = False
            ss.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        spid = instance.SpareParts_id
        ss = SpareParts.objects.get(id=spid)
        if ss.sn:
            ss.status = True
            ss.save()
        self.perform_destroy(instance)
        return Response(status=status.HTTP_204_NO_CONTENT)

    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        old_sp_id = instance.SpareParts_id
        old_ss = SpareParts.objects.get(id=old_sp_id)
        old_ss.status = True
        old_ss.save()
        self.perform_update(serializer)
        new_sp_id = instance.SpareParts_id
        new_ss = SpareParts.objects.get(id=new_sp_id)
        new_ss.status = False
        new_ss.save()

        if getattr(instance, '_prefetched_objects_cache', None):
            # If 'prefetch_related' has been applied to a queryset, we need to
            # forcibly invalidate the prefetch cache on the instance.
            instance._prefetched_objects_cache = {}

        return Response(serializer.data)


class SoReport(APIView):
    def post(self, request, *args, **kwargs):
        so_id = request.query_params['id']
        # dq = request.POST['dq']
        sr_info = SpareOut.objects.get(id=so_id)
        dir = BASE_DIR + '/static/doc/'
        doc = DocxTemplate(dir + 'template.docx')
        now = datetime.now()
        # if dq == 'hz':
        case_number = ''
        customer_name = '杭州人社'
        customer_contact = '郭健'
        phone = '13486153238'
        address = '杭州市上城区大学路99号'
        # else:
        #     case_number = 'DFZB1805148A'
        #     customer_name = '上海血液中心'
        #     customer_contact = '李超'
        #     phone = '02162955559'
        #     address = '上海市长宁区虹桥路1191号709室信息部'
        context = {
            'case_number': case_number,
            'contract_number': '',
            'customer_name': customer_name,
            'customer_contact': customer_contact,
            'phone': phone,
            'address': address,
            'y': now.now().year,
            'm': now.now().month,
            'd': now.now().day,
            'device_sn': sr_info.sn,
            'in_pn': sr_info.SpareParts.pn,
            'in_sn': sr_info.SpareParts.sn,
            'in_des': sr_info.SpareParts.model,
            'out_pn': sr_info.bad_pn,
            'out_sn': sr_info.bad_sn,
        }
        doc.render(context)
        filepath = dir + 'report.docx'
        doc.save(filepath)
        file = open(filepath, 'rb')
        response = FileResponse(file)
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = 'attachment;filename="report.docx"'

        return response
